package com.liuqi.aiagent.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.liuqi.aiagent.mapper.ChatRecordMapper;
import com.liuqi.aiagent.service.ChatRecordService;
import com.liuqi.aiagent.transfer.ApiResult;
import com.liuqi.aiagent.transfer.common.ChatResultMessage;
import com.liuqi.aiagent.transfer.entity.ChatRecord;
import com.liuqi.aiagent.transfer.model.Result;
import com.liuqi.aiagent.transfer.vo.AgentChatRecordVo;
import com.liuqi.openai.data.message.AiMessage;
import com.liuqi.openai.data.message.ChatMessage;
import com.liuqi.openai.data.message.ToolResultMessage;
import com.liuqi.openai.data.message.UserMessage;
import com.liuqi.openai.tool.ToolCallRequest;
import java.util.ArrayList;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import static com.liuqi.aiagent.util.StringUtil.hasText;

/**
 * @author liuqi
 * @date 2025/7/21
 **/
@Service
@Slf4j
@AllArgsConstructor
public class ChatRecordServiceImpl implements ChatRecordService {

    private final ChatRecordMapper chatRecordMapper;

    @Override
    public List<ChatMessage> findRecentlyOfChatMessage(String agentName, String username, int limit) {
        List<ChatRecord> recordList = chatRecordMapper.findRecently(agentName, username, limit);
        if (recordList == null || recordList.isEmpty()) {
            return null;
        }
        // AI消息组
        List<ChatMessage> chatMessages = new ArrayList<>(recordList.size() * 2);

        recordList.forEach(chatRecord -> {
            // 用户消息
            chatMessages.add(UserMessage.from(chatRecord.getInput()));

            // AI响应结果集,
            List<ChatResultMessage> results = JSONObject.parseArray(chatRecord.getOutput(), ChatResultMessage.class);

            results.forEach(result -> {
                // AI响应消息
                ChatResultMessage.AssistantMessage aiMsg = result.getAssistantMessage();
                if (aiMsg != null) {
                    // 工具调用
                    List<ToolCallRequest> requests = aiMsg.getToolCallRequests();
                    if (requests != null) {
                        chatMessages.add(AiMessage.from(aiMsg.getId(), requests));
                    }

                    // AI 响应内容
                    if (aiMsg.getContent() != null) {
                        chatMessages.add(AiMessage.from(aiMsg.getId(), aiMsg.getContent()));
                    }
                }

                // 工具调用
                ChatResultMessage.ToolCallResult res = result.getToolCallResult();
                if (res != null) {
                    chatMessages.add(ToolResultMessage.from(res.getName(), res.getToolCallId(), res.getResult()));
                }
            });

        });

        return chatMessages;
    }

    @Override
    public Result<List<AgentChatRecordVo>> findRecentlyOfVo(String agentName, String username, int limit) {
        List<ChatRecord> recordList = chatRecordMapper.findRecently(agentName, username, limit);
        if (recordList == null || recordList.isEmpty()) {
            return ApiResult.success(new ArrayList<>(0));
        }

        // 聊天记录转换成 AgentChatRecordVo
        List<AgentChatRecordVo> chatRecordVos = new ArrayList<>(recordList.size() * 2);

        recordList.forEach(chatRecord -> {
            // 添加用户消息
            chatRecordVos.add(AgentChatRecordVo.userMsg(chatRecord.getInput()));

            // AI响应结果集, 需要构建出 extendMsgs
            List<ChatResultMessage> results = JSONObject.parseArray(chatRecord.getOutput(), ChatResultMessage.class);
            List<AgentChatRecordVo.ExtendMsg> extendMsgs = new ArrayList<>();
            results.forEach(result -> {
                ChatResultMessage.AssistantMessage aiMsg = result.getAssistantMessage();
                if (aiMsg != null) {
                    if (hasText(aiMsg.getReasoningContent())) {
                        // 思考内容
                        extendMsgs.add(new AgentChatRecordVo.Think(aiMsg.getReasoningContent(), aiMsg.getThinkDuration()));
                    }
                    if (aiMsg.getToolCallRequests() != null && !aiMsg.getToolCallRequests().isEmpty()) {
                        // 工具调用
                        aiMsg.getToolCallRequests().forEach(request -> {
                            extendMsgs.add(new AgentChatRecordVo.ToolCall(
                                    new AgentChatRecordVo.ToolCall.Function(request.getName(), request.getArguments())
                            ));
                        });
                    }
                    if (hasText(aiMsg.getContent())) {
                        // 添加AI消息
                        chatRecordVos.add(AgentChatRecordVo.aiMsg(aiMsg.getContent(), extendMsgs));
                    }
                }
            });

        });

        return ApiResult.success(chatRecordVos);
    }

    @Override
    public Result deleteByAgentNameAndUsername(String agentName, String username) {
        int delete = chatRecordMapper.deleteByAgentNameAndUsername(agentName, username);
        if (delete > 0) {
            log.info("用户[{}]删除Agent[{}]聊天记录成功, 删除记录数[{}]", username, agentName, delete);
        }
        return ApiResult.success();
    }
}
